import 'dart:math';

class MoneyUtils {
  /// 金额格式化方法
  static String amountFormat(dynamic number, [int fixed = 2]) {
    if (number is num) {
      String res = "";
      res = number.toString();
      // number不存在时直接返回0
      if (res.isEmpty) {
        res = "0";
        if (fixed > 0) {
          res += ".";
          for (int i = 0; i < fixed; i++) {
            res += "0";
          }
        }
      }

      int size = res.split(".")[0].length;
      if (size < 5) {
        res = number.toStringAsFixed(fixed);
      } else if (size >= 5 && size < 8) {
        res = "${(number / pow(10, 4)).toStringAsFixed(fixed)}万";
      } else if (size == 8) {
        res = "${(number / pow(10, 7)).toStringAsFixed(fixed)}千万";
      } else {
        res = "${(number / pow(10, 8)).toStringAsFixed(fixed)}亿";
      }
      return res;
    } else {
      var suffix = "";
      number = number.toString();

      // number不存在时直接返回0
      if (number.isEmpty) number = "0";
      // 记录正负符号
      if (number.contains("-")) suffix = "-";
      var numbers = RegExp(r'[^\d+\-Ee.]');
      number = number.replaceAll(numbers, "").replaceAll("-", "");
      int size = number.split(".")[0].length;
      number = double.parse(number);
      if (size < 5) {
        number = number.toStringAsFixed(fixed);
      } else if (size >= 5 && size < 8) {
        number = "${(number / pow(10, 4)).toStringAsFixed(fixed)}万";
      } else if (size == 8) {
        number = "${(number / pow(10, 7)).toStringAsFixed(fixed)}千万";
      } else {
        number = "${(number / pow(10, 8)).toStringAsFixed(fixed)}亿";
      }
      number = suffix + number;
      return number;
    }
  }
}
